﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Web;
using Baidu.API.Entity;

namespace Baidu.API {
    public class Translate {
        /// <summary>
        /// 禁止实例化
        /// </summary>
        private Translate() { }


        public static TransResult Trans(string words, string from = "auto", string to = "auto") {
            var result = Query(words, from, to);
            return JsonHelper.JsonDeserialize<TransResult>(result);
        }

        /// <summary>
        /// 调用百度翻译API http://developer.baidu.com/wiki/index.php?title=%E5%B8%AE%E5%8A%A9%E6%96%87%E6%A1%A3%E9%A6%96%E9%A1%B5/%E7%99%BE%E5%BA%A6%E7%BF%BB%E8%AF%91/%E7%BF%BB%E8%AF%91API
        /// </summary>
        /// <param name="words"></param>
        /// <param name="from">可选: auto zh jp spa th ru yue zh de en kor fra ara pt wyw it</param>
        /// <param name="to">可选: auto zh jp spa th ru yue zh de en kor fra ara pt wyw it</param>
        /// <returns></returns>
        private static string Query(string words, string from = "auto", string to = "auto") {
            const string baseUrl = "http://openapi.baidu.com/public/2.0/bmt/translate";

            var queryString = new QueryString();
            queryString.Add("from", from);
            queryString.Add("to", to);
            queryString.Add("client_id", Config.API_KEY);
            queryString.Add("q", HttpUtility.UrlEncode(words));

            var hc = new HttpClient();

            var task = hc.GetStringAsync(string.Format(@"{0}?{1}", baseUrl, queryString));
            return task.Result;
        }

        ///// <summary>
        ///// 调用百度翻译API http://developer.baidu.com/wiki/index.php?title=%E5%B8%AE%E5%8A%A9%E6%96%87%E6%A1%A3%E9%A6%96%E9%A1%B5/%E7%99%BE%E5%BA%A6%E7%BF%BB%E8%AF%91/%E7%BF%BB%E8%AF%91API
        ///// </summary>
        ///// <param name="words"></param>
        ///// <param name="from">可选: auto zh jp spa th ru yue zh de en kor fra ara pt wyw it</param>
        ///// <param name="to">可选: auto zh jp spa th ru yue zh de en kor fra ara pt wyw it</param>
        ///// <returns></returns>
        //private async static Task<string> Query(string words, string from = "auto", string to = "auto"){
        //    const string baseUrl = "http://openapi.baidu.com/public/2.0/bmt/translate";

        //    var queryString = new QueryString();
        //    queryString.Add("from", from);
        //    queryString.Add("to", to);
        //    queryString.Add("client_id",Config.API_KEY);
        //    queryString.Add("q", HttpUtility.UrlEncode(words));

        //    var hc = new HttpClient();

        //    var task = await hc.GetStringAsync(string.Format(@"{0}?{1}", baseUrl, queryString));
        //    return task;
        //}
    }
}
